<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\ImageRequest;
use Consatan\Weibo\ImageUploader\Client;
use CURLFile;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

class ImagesController extends Controller
{

    public function store(ImageRequest $request)
    {







//        if (preg_match('/^[\x{4e00}-\x{9fa5}]+$/u', $originalName) > 0) {
//            $originalName = \chinese2pinyin::encode($originalName);
//        } elseif (preg_match('/[\x{4e00}-\x{9fa5}]/u', $originalName) > 0) {
//            $originalName = \chinese2pinyin::encode($originalName);
//        }
//        echo md5($originalName) . "." . $request->image->getClientOriginalExtension();exit;

        //storage_path返回根目录下的storage的绝对路径 里面放的直接丢在后面
//        $filePath = storage_path('app/' . $path);
//        echo base_path();exit;
//        echo $path;exit;
        //上传到七牛
//        $ret = qiniu_upload($filePath);  //调用的全局函数
//        Storage::move($path,"../../mb.jpg");
//        print_r($ret);
//        exit;


        $originalName = $request->image->getClientOriginalName();
        $path = $request->image->storeAs('', md5($originalName) . "." . $request->image->getClientOriginalExtension());
        $filePath = base_path() . "/public/uploads/" . $path;
        $weibo = new Client();
        $url = $weibo->upload($filePath, '13163731801', 'super2010');
        echo $url; exit;


        $res = $this->upload_file("localhost:3000/upload", $filePath, $request->image->getClientOriginalExtension());
        echo $res;exit;

//        return $this->response->array([
//            'url' => "http://" . $request->server('HTTP_HOST') . "/uploads/" . $path
//        ]);
    }

    /**
     *  curl文件上传
     * @var  struing $r_file 上传文件的路劲和文件名
     *
     */
    public function upload_file($url, $r_file)
    {
        $data = array('file'=>new CURLFile($r_file));
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        $content = curl_exec($curl);
        curl_close($curl);
        return $content;
    }

}
